package top.zhongyy.util;

import com.github.jarod.qqwry.IPZone;
import com.github.jarod.qqwry.QQWry;
import eu.bitwalker.useragentutils.UserAgent;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Created by IntelliJ IDEA.
 * @DESC:IP工具类
 * @Author: Andy
 * @Date: 2021/4/1
 */
public class IPUtils {
    private static final char SEPARATOR = '_';
    
    private static final String UNKNOWN = "unknown";
    
    public static void main(String[] args) throws Exception {
        System.out.println(IPUtils.getInterIP1());
        System.out.println(IPUtils.getInterIP2());
        System.out.println(IPUtils.getOutIPV4());
    }
    
    /**
     * @Desc: 获取内网IP
     * @author Andy
     * @date: 2021/4/1 22:23
     */
    public static String getInterIP1() throws Exception {
        return InetAddress.getLocalHost().getHostAddress();
    }
    
    public static String getInterIP2() throws SocketException {
        String localip = null;// 本地IP，如果没有配置外网IP则返回它
        String netip = null;// 外网IP
        Enumeration<NetworkInterface> netInterfaces;
        netInterfaces = NetworkInterface.getNetworkInterfaces();
        InetAddress ip = null;
        boolean finded = false;// 是否找到外网IP
        while (netInterfaces.hasMoreElements() && !finded) {
            NetworkInterface ni = netInterfaces.nextElement();
            Enumeration<InetAddress> address = ni.getInetAddresses();
            while (address.hasMoreElements()) {
                ip = address.nextElement();
                if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {// 外网IP
                    netip = ip.getHostAddress();
                    finded = true;
                    break;
                } else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {// 内网IP
                    localip = ip.getHostAddress();
                }
            }
        }
        if (netip != null && !"".equals(netip)) {
            return netip;
        } else {
            return localip;
        }
    }
    
    /**
     * @Desc: 外网IP, 不可用, 需付费!!!
     * @author Andy
     * @date: 2021/4/1 22:23
     */
    public static String getOutIPV4() {
        String ip = "";
        String chinaz = "http://ip.chinaz.com";
        
        StringBuilder inputLine = new StringBuilder();
        String read = "";
        URL url = null;
        HttpURLConnection urlConnection = null;
        BufferedReader in = null;
        try {
            url = new URL(chinaz);
            urlConnection = (HttpURLConnection) url.openConnection();
            in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
            while ((read = in.readLine()) != null) {
                inputLine.append(read + "\r\n");
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        Pattern p = Pattern.compile("\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");
        Matcher m = p.matcher(inputLine.toString());
        if (m.find()) {
            String ipstr = m.group(1);
            ip = ipstr;
        }
        return ip;
    }
    
    /**
     * @param request
     * @Desc: 获取真实IP
     * @author Andy
     * @date: 2021/4/2 13:32
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        String comma = ",";
        String localhost = "127.0.0.1";
        if (ip.contains(comma)) {
            ip = ip.split(",")[0];
        }
        if (localhost.equals(ip)) {
            // 获取本机真正的ip地址
            try {
                ip = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }
        return ip;
    }
    
    /**
     * @param IPV4
     * @Desc: 获取ip所对应的地址
     * @author Andy
     * @date: 2021/4/2 13:30
     */
    public static String getAddress(String IPV4) throws IOException {
        QQWry wry = new QQWry();
        IPZone zone = wry.findIP(IPV4);
        return zone.getMainInfo();
    }
    
    /**
     * @param IPV4
     * @Desc: 获取运营商
     * @author Andy
     * @date: 2021/4/2 13:30
     */
    public static String getOperator(String IPV4) throws IOException {
        QQWry wry = new QQWry();
        IPZone zone = wry.findIP(IPV4);
        return zone.getSubInfo();
    }
    
    /**
     * @param request
     * @Desc: 获取浏览器内核   例: chrome 8,Chrome Mobile
     * @author Andy
     * @date: 2021/4/2 13:31
     */
    public static String getBrowser(HttpServletRequest request) {
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        return userAgent.getBrowser().getName();
    }
    
    /**
     * @param request
     * @Desc: 获取浏览客户端OS 例:Windows 10 ,Android 1.x
     * @author Andy
     * @date: 2021/4/2 13:31
     */
    public static String getClientOS(HttpServletRequest request) {
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        return userAgent.getOperatingSystem().getName();
    }
}
